<?php
/**
 * Create a new company
 * 
 * @author Xavier VILAIN
 * @package Hive\Company
 * @license #license-hive#
 * 
 */
use Hive\Company;
use Fox\Html\Input;
use Fox\Dao\SqlFragment;
use Fox\Generator;
use Fox\Html\Screen;
$xview = Xview::instance();
$screen = new Screen('sCompany','create');
$screen->pageTitle(Msg(Hive::BUNDLE,Hive::COMPANY_CREATION));
$block = $xview->component('company', 'header');
$block->remove('logo');
$block->remove('company_parent');

$screen->add($block);
// Address Data
$blAddress = $xview->component(Company::BUNDLE, 'address');
$screen->add($blAddress);

if($screen->submitted()) {
	$inputs = $screen->get();
	$warning = false;
	if(!$screen->errors()) {
		$result = Company::lookup($inputs['company_name']);
		if($result) {
			$warning = true;
			$cpMg = '<a href="?mod=company&act=main&cpid='.$result->compid.'">'.$result->company_name.'</a>';
			Fox\Message::Warning(Msg(Hive::BUNDLE,Hive::A_COMPANY_X1_ALREADY_EXISTS_WITH_THIS_NAME,$cpMg));
		}
	}
	if(!$screen->errors()) {
		$inputs = Fox\Utilities::arrayTrim($inputs);
		$grouping = $block->item('grouping');
		try {
			$handle = Fox\Dao::infos(Hive\Company::className())->handle();
			$handle->beginTransaction();
			// Check if the school already exist
			$company = new Hive\Company();
			$company->setFields($inputs);
			$address = new Fox\Common\Address();
			$address->setFields($inputs);
			$address->create();
			$company->create();
			$adressLink = new \Hive\Company\Address\Link();
			$adressLink->setFields(array(
				'compid' => $company->getId(),
				'adrid' => $address->getId(),
				'type' => Company::ADDRESS_TYPE_DEFAULT
			));
			$adressLink->create();
			$handle->commit();
			Fox\Message::Success(Msg(Fox\Msg::BUNDLE,Fox\Msg::MSG_CREATE,$company->company_name));
			$screen->redirect(Generator::url('company','main',null,array('cpid' => $company->getId())));
		}
		catch(Fox\Object\Exception\Save $e) {
			Fox\Message::Error($e);
		}
	}
}
echo $screen->Display();